<?php
class MenuController extends Zend_Controller_Action {
	public function indexAction() {
		$auth = Zend_Auth::getInstance();
		$identity = $auth->getIdentity();
		$menu = NULL;
		if($identity!==null) {
			$cache = new Memcache();
			$cache->connect('localhost',11211) or null;
			if(isset($cache) && $cache->get('menu')) {
				$buffer = $cache->get('menu');
				$ruleid = Core_Business_Rule::getRuleByName($identity->getRole())->Id;
				$menu = isset($buffer[$ruleid]) ? $buffer[$ruleid] : NULL;
			}
			if($menu === NULL)
			{
				$rootmenu = Core_Business_Rulemenu::getMenuitemLevel0(Core_Business_Rule::getRuleByName($identity->getRole())->Id);
				$menu = $this->assemble($rootmenu);
				if(isset($cache)) {
					$buffer = isset($buffer) ? $buffer : array();
					$buffer[Core_Business_Rule::getRuleByName($identity->getRole())->Id] = $menu;	 
					$cache->set("menu",$buffer,false,1800);
				}
			}
			//$menu2 = array(array('title'=>'Recherche','url'=>'/default/Search','sub'=>array()),array('title'=>'Formation','url'=>'#','sub'=>array(array('group'=>'Edition','title'=>'Add','url'=>'/default/training/add','sub'=>array()),array('title'=>'list','url'=>'/default/training','sub'=>array()))));
		}	
		$this->view->menu = $menu;
		$loggedInUser = new Core_Common_Views_Helpers_LoggedInUser();
		$this->view->registerHelper($loggedInUser,'LoggedInUser');
		$this->_helper->viewRenderer->setResponseSegment('menu');
	}
	
	protected function assemble($root) {
		$menu = array();
		foreach ($root as $item) {
			if($item->Disabled==0 && Core_Business_Rulemenu::allow($item, Core_Business_Rule::getRuleByName($this->_helper->Acl->getUser()->getRole())->Id)==true) {
				$aritem = array("title"=>$item->Label,"url"=>$item->Url);
				$child = $item->getChild();
				$sub=array();
				if(isset($child)) {
					$nextlevel = $this->assemble($child);
					$sub=$nextlevel;
				}
				$aritem["sub"]=$sub;
				$menu[]=$aritem;
			}
		}
		//var_dump($menu);
		return $menu;
	}
}